<template>
  <div class="kpi-atom">
    <div class="kpi-list-wrap clearfix">
      <div class="bussiness-list">
        <div class="table-selecor">
          加工表：
          <el-select v-model="selectTable">
            <el-option label="---" value=""></el-option>
            <el-option
              v-for="item in tableList"
              :key="item.tableNm"
              :label="item.tableNm"
              :value="item.tableNm"
            ></el-option>
          </el-select>
        </div>
        <el-collapse v-model="type" accordion>
          <el-collapse-item name="all" title="全部字段">
            <template v-if="fieldList.length">
              <el-input v-model="fieldKeyword" placeholder="搜索字段" clearable></el-input>
              <ul class="field-list tag-scrollbar">
                <li v-for="item in showFieldList" :key="item.fieldNm" draggable @dragstart="copyDragList($event, item)">
                  {{ item.fieldNm }}
                  <div class="list-handler">
                    <el-tooltip effect="dark" content="添加" placement="top" :enterable="false">
                      <span class="plus" @click.prevent="addItem(item)"><i class="el-icon-plus"></i></span>
                    </el-tooltip>
                  </div>
                </li>
              </ul>
            </template>
            <div class="no-record" v-else>
              <template v-if="selectTable">
                <img src="~@/assets/img/no_records.png" /><br />
                暂无内容
              </template>
              <template v-else>
                请先选择加工表
              </template>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="kpi-list">
        <div class="list-title"><icon-svg name="iconFunc"></icon-svg> 函数（fx）</div>
        <el-input v-model="keyword" placeholder="输入搜索关键字" @keyup.native.enter="search">
          <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
          <el-button slot="append" @click="search"><icon-svg name="iconSearch"></icon-svg></el-button>
        </el-input>
        <ul class="kpi-func-list tag-scrollbar">
          <li v-for="item in funcList" :key="item.funcId" draggable @dragstart="copyDrag($event, item)">
            <div class="func-name">{{ item.funcExpression }}</div>
            <div class="list-handler">
              <el-tooltip effect="dark" content="添加" placement="top" :enterable="false">
                <span class="plus" @click="addFunc(item)"><i class="el-icon-plus"></i></span>
              </el-tooltip>
              <el-tooltip effect="dark" placement="top" :content="item.funcDeclaration" :enterable="false">
                <icon-svg name="iconEvent"></icon-svg>
              </el-tooltip>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <atom-content ref="atomContent" :logicalList="logicalList"></atom-content>
  </div>
</template>

<script>
import atomContent from './atom-content'
export default {
  components: {
    atomContent
  },
  data() {
    return {
      selectTable: '',
      type: 'all',
      tableList: [],
      fieldList: [],
      fieldKeyword: '',
      keyword: '',
      operatorListCopy: [],
      operatorList: []
    }
  },
  created() {
    Promise.all([this.getTable(), this.getOperator()]).then(() => this.$refs.atomContent.init())
  },
  watch: {
    selectTable() {
      this.fieldKeyword = ''
      this.getFieldList()
    }
  },
  computed: {
    logicalList() {
      return this.operatorList.filter(item => item.funcType === 1)
    },
    funcList() {
      return this.operatorList.filter(item => item.funcType === 2)
    },
    showFieldList() {
      return this.fieldKeyword.trim()
        ? this.fieldList.filter(item => item.fieldNm.indexOf(this.fieldKeyword.trim()) >= 0)
        : this.fieldList
    }
  },
  methods: {
    getTable() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('der/derKpiType/getAllTable'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.tableList = data.data
            resolve()
          } else {
            this.$message.error(data.data || data.msg)
            reject()
          }
        })
      })
    },
    getFieldList() {
      const tableItem = this.tableList.find(item => item.tableNm === this.selectTable)
      this.$ajax({
        url: this.$ajax.setUrl('der/derKpiType/getTableFields'),
        method: 'post',
        data: this.$ajax.setData({
          dbName: tableItem.dbName,
          plfmId: tableItem.plfmId,
          relaField: tableItem.relaField,
          tableNm: tableItem.tableNm,
          tableType: tableItem.tableType
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.fieldList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getOperator() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('IndexAllocation/getDerCalculationFunction'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.operatorListCopy = Array.from(data.data)
            this.operatorList = Array.from(data.data)
            resolve()
          } else {
            this.$message.error(data.msg)
            reject()
          }
        })
      })
    },
    updateTable(table) {
      this.selectTable = table
    },
    search() {
      this.operatorList = this.keyword.trim().length
        ? this.operatorList.filter(
            item => item.funcType === 1 || item.funcExpression.toLowerCase().includes(this.keyword.toLowerCase())
          )
        : Array.from(this.operatorListCopy)
    },
    clearSearch() {
      this.keyword = ''
      this.search()
    },
    addItem(item) {
      this.$refs.atomContent.addItem(
        Object.assign({}, { labTbl: item.tableNm, labFldMap: item.fieldNm }, { type_id: '1' })
      )
    },
    addFunc(item) {
      this.$refs.atomContent.addItem(Object.assign({}, item, { type_id: '2' }))
    },
    copyDragList(event, item) {
      event.dataTransfer.setData('type_id', '1')
      event.dataTransfer.setData('labTbl', item.tableNm)
      event.dataTransfer.setData('labFldMap', item.fieldNm)
    },
    copyDrag(event, item) {
      event.dataTransfer.setData('type_id', '2')
      event.dataTransfer.setData('func_config', JSON.stringify(item))
    }
  }
}
</script>

<style lang="scss">
@import './atom.scss';
</style>
